//
//  TTHttpRequest.m
//  ExhibitionHall
//
//  Created by 王洋 on 2019/6/3.
//  Copyright © 2019 王洋. All rights reserved.
//
#import "NSDate+InternetDateTime.h"
#import "TTUserModel.h"
#import "AFNetworking.h"
#import "TTHttpRequest.h"
#import "TTUDIDManager.h"
#import "LoginViewController.h"

@implementation TTHttpRequest

- (void)getStart {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10.0;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];
    
    [manager GET:self.url parameters:self.getData headers:@{} progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *jsonDict = [Utilities dictionaryWithJsonString:responseObject];
            self.finishBlock(jsonDict);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            self.failedBlock(error);
        }];
}

- (void)postStart {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10.0;

    manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;

    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"text/plain", nil];
    
    if ([TTUserModel sharedObject].users.count > 0 && [TTUserModel sharedObject].users.firstObject.Access_Token.length > 0) {
        
        NSString *token = @"";
        NSString *newStr = [NSString stringWithFormat:@"%ld%@%@",(long)[Utilities getCurrentTimestamp],token,@"1qaz@WSX"];
        NSString *t = [NSString stringWithFormat:@"/Date(%ld)/",(long)[Utilities getCurrentTimestamp]];
        NSString *c = [Utilities NeteaseMd5:newStr];
        
        NSMutableDictionary *map = @{}.mutableCopy;
        [map setValue:token forKey:@"token"];
        [map setValue:t forKey:@"t"];
        [map setValue:c forKey:@"c"];
        
        NSString *map_jsonStr = [Utilities stringWithDictionary:map];
        [self.postData setValue:map_jsonStr forKey:@"access_token"];
    }
    
    
    [manager POST:self.url parameters:self.postData headers:@{} progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *jsonDict = [Utilities dictionaryWithJsonString:responseObject];
            self.finishBlock(jsonDict);
            [self refreshTimeWithTask:task AndID:responseObject];

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            self.failedBlock(error);
        }];
}



- (void)refreshTimeWithTask:(NSURLSessionDataTask * _Nonnull) task AndID:(id _Nullable)responseObject {
    
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
    NSDictionary *allHeaders = response.allHeaderFields;
    NSString *dateServer = [allHeaders valueForKey:@"Date"];
    NSDate *inputDate = [NSDate dateFromRFC822String:dateServer];
    NSTimeInterval serverTimeStamp = [Utilities getTimestampWithDate:inputDate];
    [[NSUserDefaults standardUserDefaults] setDouble:serverTimeStamp forKey:@"kLastSaveServerTimeStamp"];
    NSTimeInterval currentLocalTimeStamp = [Utilities getCurrentTimestamp];
    
    [[NSUserDefaults standardUserDefaults] setDouble:currentLocalTimeStamp forKey:@"kLastSaveLocalTimeStamp"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
